#拟合误差
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
from tornado.web import RequestHandler
import json
import common as com
from logHandler import getLogger
from timeoutHandler import set_timeout

class ErrorOfFittingVo(object):
    def __init__(self, trainDataList):
        self.trainDataList = trainDataList

def dictToErrorOfFittingVo(d):
    return ErrorOfFittingVo(d["trainDataList"])

class ErrorOfFittingHandler(RequestHandler):
    @set_timeout(com.timeoutTime)
    def post(self):
        try:
            jsonByte = self.request.body
            jsonStr = jsonByte.decode("utf-8")
            errorOfFittingVo = json.loads(jsonStr, object_hook=dictToErrorOfFittingVo)
            log = getLogger()
            log.info("开始拟合误差算法：{}".format(errorOfFittingVo.__dict__))
            data_array = errorOfFittingVo.trainDataList
            predictDataList = []
            for data_line in data_array:
                data_info = data_line.split("_")
                station_id = data_info[0]
                x_test = np.asarray(data_info[1], dtype=np.float32)
                x_train = np.asarray(data_info[2].split(","), dtype=np.float32)
                y_train = np.asarray(data_info[3].split(","), dtype=np.float32)
                clf = Pipeline([('poly', PolynomialFeatures(degree=2)),
                                ('linear', LinearRegression(fit_intercept=False))])
                clf.fit(x_train.reshape(-1, 1), y_train.reshape(-1, 1))
                y_predict = clf.predict(x_test.reshape(-1, 1))
                siteData = com.SiteData(str(station_id), str(y_predict[0][0]))
                predictDataList.append(siteData.__dict__)
            commonResponse = com.CommonResponse(com.successCode, com.successMsg, dict([("list", predictDataList)]))
            log.info("拟合误差算法执行完毕")
        except BaseException as e:
            print("执行拟合误差算法失败：{}".format(e))
            commonResponse = com.CommonResponse(com.errorCode, "{}".format(e), dict([("obj", com.missingValues)]))
            log.error("拟合误差算法执行异常")
        finally:
            # 返回数据
            self.write(commonResponse.__dict__)